﻿using System;
using System.Reflection;
using System.Windows.Controls;

namespace CAION2.Views
{
    /// <summary>
    /// Interaction logic for Recepture_Page.xaml
    /// </summary>
    public partial class RecepturePage
    {
        public RecepturePage()
        {
            InitializeComponent();
        }

        


        //private void ReceptureTreeLoaded(object sender, RoutedEventArgs e)
        //{
        //    (sender as TreeView).SetAlternationIndexRecursively(1);
        //}

        //private void ExpanderOnClick(object sender, RoutedEventArgs e)
        //{
        //    ReceptureTreeView.SetAlternationIndexRecursively(1);
        //}

        //private void ReceptureTreeSourceUpdated(object sender, DataTransferEventArgs e)
        //{
        //    ReceptureTreeView.SetAlternationIndexRecursively(1);
        //}

        //private void ReceptureTreeOnLayoutUpdated(object sender, EventArgs e)
        //{
        //    ReceptureTreeView.SetAlternationIndexRecursively(1);
        //}

        public void Connect(int connectionId, object target)
        {
            throw new NotImplementedException();
        }
    }

    public static class AlternationExtensions
    {
        private static readonly MethodInfo SetAlternationIndexMethod;

        static AlternationExtensions()
        {
            SetAlternationIndexMethod = typeof(ItemsControl).GetMethod(
            "SetAlternationIndex", BindingFlags.Static | BindingFlags.NonPublic);
        }

        public static int SetAlternationIndexRecursively(this ItemsControl control, int firstAlternationIndex)
        {
            if (control == null) return 0;

            var alternationCount = control.AlternationCount;
            if (alternationCount == 0) return 0;

            foreach (var item in control.Items)
            {
                var container = control.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                if (container == null) continue;

                var nextAlternation = firstAlternationIndex++ % alternationCount;
                SetAlternationIndexMethod.Invoke(null, new object[] { container, nextAlternation });
                if (container.IsExpanded) firstAlternationIndex = SetAlternationIndexRecursively(container, firstAlternationIndex);
            }

            return firstAlternationIndex;
        }
    }
}
